<?php


namespace app\user\controller;


use app\common\Tools;
use think\Db;
use think\facade\Request;

/**
 * Class Client 客户管理
 * @package app\user\controller
 */
class Client extends LoggingBase
{
    #region 界面
    public function Index()
    {
        return $this->mb_Display('客户管理', 'ClientManager');
    }

    /**
     * 我的客户
     */
    public function MyClient()
    {
        $GroupID = Request::has('GroupID') ? Request::param('GroupID') : 0; //0:全部，Other：对应GroupID
        $this->assign('GroupID', $GroupID);
        //我的直接下级员工
        $UserID = $this->m_User->ID;
        $SuperiorID = $this->m_User->ID;
        $CompanyID = $this->m_User->CompanyID;
        $StaffData = Db::table('user')->field('ID,Name,Nick')->where("IsDeleted='0' AND CompanyID='$CompanyID' AND ID!='$UserID'")->select();
        $this->assign('StaffData', $StaffData);

        $GroupData[] = ['ID' => 0, 'Name' => '全部'];
        $GroupData = array_merge($GroupData, Db::table('group_client')->field('ID,Name')->where("IsDeleted='0' AND UserID='$UserID'")->select());
        $this->assign('GroupData', $GroupData);

        $this->assign('Today', date('Y-m-d'));
        $Css = array(
            '<link href="/layui/css/layui.css" rel="stylesheet"/>'
        );
        $Js = array(
            '<script src="/js/user/client.js"></script>'
        );
        return $this->mb_Display('我的客户', 'MyClient', 'my_client', $Css, $Js);
    }

    /**
     * 公海客户
     */
    public function PubClient()
    {
        //我的直接下级员工
        $UserID = $this->m_User->ID;
        $SuperiorID = $this->m_User->ID;
        $CompanyID = $this->m_User->CompanyID;
        $StaffData = Db::table('user')->field('ID,Name,Nick')->where("IsDeleted='0' AND CompanyID='$CompanyID' AND ID!='$UserID'")->select();
        $this->assign('StaffData', $StaffData);
        $this->assign('Today', date('Y-m-d'));

        $Css = array(
            '<link href="/layui/css/layui.css" rel="stylesheet"/>'
        );
        $Js = array(
            '<script src="/js/user/client.js"></script>'
        );
        return $this->mb_Display('公海客户', 'PubClient', 'pub_client', $Css, $Js);
    }

    /**
     * 公司客戶
     */
    public function CompanyClient()
    {
        //我的直接下级员工
        $SuperiorID = $this->m_User->ID;
        $StaffData = Db::table('user')->field('ID,Name,Nick')->where("IsDeleted='0' AND (SuperiorID='$SuperiorID' OR ID='$SuperiorID')")->select();
        $this->assign('StaffData', $StaffData);
        $this->assign('Today', date('Y-m-d'));
        $Css = array(
            '<link href="/layui/css/layui.css" rel="stylesheet"/>'
        );
        $Js = array(
            '<script src="/js/user/client.js"></script>'
        );
        return $this->mb_Display('公司客戶', 'CompanyClient', 'company_client', $Css, $Js);
    }

    /**
     * 待拨打列表
     */
    public function CallList()
    {
        $Css = array(
            '<link href="/layui/css/layui.css" rel="stylesheet"/>'
        );
        return $this->mb_Display('待拨打列表', 'CallList', 'call_list', $Css);
    }

    /**
     * 通话记录
     */
    public function CallRecord()
    {
        $Css = array(
            '<link href="/layui/css/layui.css" rel="stylesheet"/>'
        );
        return $this->mb_Display('通话记录', 'CallRecord', 'call_record', $Css);
    }

    /**
     * 客戶详情
     */
    public function ClientDetail()
    {
        $ClientID = Request::has('ClientID') ? Request::param('ClientID') : 0;
        $From = Request::has('From') ? Request::param('From') : '';
        if (!$ClientID) mb_OutMessage(ErrCode_Toast, '参数错误');

        $Css = array(
            '<link href="/layui/css/layui.css" rel="stylesheet"/>'
        );
        return $this->mb_Display('客戶详情', $From, 'client_detail', $Css);

//        $Css = array();
//        $Js = array();
//        $this->assign('Css', $Css);
//        $this->assign('Js', $Js);
//
//        return $this->fetch('client_detail');
    }
    #endregion

    #region 接口

    /**
     * 新建或编辑客户分组
     */
    public function mb_SubmitGroup()
    {
        $ID = Request::has('ID') ? Request::param('ID') : 0;
        $Name = Request::has('Name') ? Request::param('Name') : '';
        if (!$Name) mb_OutMessage(ErrCode_Toast, '请输入分组名');

        Db::startTrans();
        try {
            $Data = array(
                'UserID' => $this->m_User->ID,
                'Name' => $Name
            );
            if ($ID == 0) {
                //新增
                Db::table('group_client')->insert($Data);
            } else {
                //编辑
                $Data['ID'] = $ID;
                Db::table('group_client')->update($Data);
            }
            Db::commit();
            mb_OutMessage(ErrCode_Normal, '保存成功');
        } catch (\Exception $e) {
            Db::rollback();
            mb_OutMessage(ErrCode_Toast, $e->getMessage());
        }
    }

    /**
     * 删除分组
     */
    public function mb_DeleteGroup()
    {
        $GroupID = Request::has('GroupID') ? Request::param('GroupID') : 0;
        if (!$GroupID) mb_OutMessage(ErrCode_Toast, '参数错误');

        Db::startTrans();
        try {
            Db::table('client')->where("IsDeleted='0' AND GroupID='$GroupID'")->update(['GroupID' => 0]);
            Db::table('group_client')->update(['ID' => $GroupID, 'IsDeleted' => 1]);
            Db::commit();
            mb_OutMessage(ErrCode_Normal, '删除成功');
        } catch (\Exception $e) {
            Db::rollback();
            mb_OutMessage(ErrCode_Toast, $e->getMessage());
        }
    }

    /**
     * 转移分组
     */
    public function mb_ChangeGroup()
    {
        $ClientIDs = Request::has('ClientIDs') ? Request::param('ClientIDs') : '';
        $GroupID = Request::has('GroupID') ? Request::param('GroupID') : 0;
        if ($ClientIDs == '') mb_OutMessage(ErrCode_Toast, '请选择客户');

        Db::startTrans();
        try {
            Db::table('client')->where("IsDeleted='0' AND ID IN ( $ClientIDs )")->update(['GroupID' => $GroupID]);
            Db::commit();
            mb_OutMessage(ErrCode_Normal, '操作成功');
        } catch (\Exception $e) {
            Db::rollback();
            mb_OutMessage(ErrCode_Toast, $e->getMessage());
        }
    }

    /**
     * 获取跟进记录
     */
    public function mb_GetFollowList(){
        $ClientID = Request::has('ClientID')?Request::param('ClientID'):0;
        if(!$ClientID)mb_OutMessage(ErrCode_Toast,'请选择要查看的客户');

        $Page = Request::has('Page') ? Request::param('Page') : 1;
        $Limit = Request::has('Limit') ? Request::param('Limit') : 10;

        $Count = Db::table('client_follow')->field('ID')->where("IsDeleted='0' AND ClientID='$ClientID'")->count();
        $Data = Db::table('client_follow')->field('cf.ID,u.ID AS UserID, u.Nick AS UserNick, cf.Content, cf.TimeCreated')->alias('cf')->leftJoin('user u','u.ID=cf.UserID')
            ->where("cf.IsDeleted='0' AND cf.ClientID='$ClientID'")->order('ID','DESC')->page($Page)->limit($Limit)->select();
        mb_OutMessage(ErrCode_Normal, '', $Data, $Count);
    }

    public function mb_AddFollow(){
        $ClientID = Request::has('ClientID') ? Request::param('ClientID') : 0;
        $Content = Request::has('Content') ? Request::param('Content') : '';
        if (!$ClientID) mb_OutMessage(ErrCode_Toast, '请选择客户');
        if (!$Content) mb_OutMessage(ErrCode_Toast, '请填写跟进内容');

        $UserID = $this->m_User->ID;
        Db::startTrans();
        try {
            Db::table('client_follow')->insert(['UserID'=>$UserID,'ClientID'=>$ClientID,'Content'=>$Content]);
            Db::commit();
            mb_OutMessage(ErrCode_Normal, '保存成功');
        } catch (\Exception $e) {
            Db::rollback();
            mb_OutMessage(ErrCode_Toast, $e->getMessage());
        }
    }

    /**
     * 我的客戶
     */
    public function mb_MyClientList()
    {
        $Page = Request::has('page') ? Request::param('page') : 1;
        $Limit = Request::has('limit') ? Request::param('limit') : 10;
        $Keyword = Request::has('Keyword') ? Request::param('Keyword') : '';
        $TimeCreated = Request::has('TimeCreated') ? Request::param('TimeCreated') : '';

        $OrderField = Request::has('OrderField') ? Request::param('OrderField') : '';
        $OrderType = Request::has('OrderType') ? Request::param('OrderType') : '';

        $GroupID = Request::has('GroupID') ? Request::param('GroupID') : 0;
        $Where = '';
        if ($Keyword != '') {
            $Where .= " AND (c.Name LIKE '%$Keyword%' OR c.Phone LIKE '%$Keyword%') ";
        }
        if ($TimeCreated != '') {
            $Where .= " AND DATE_FORMAT(c.TimeCreated,'%Y-%m-%d')='$TimeCreated' ";
        }
        if($GroupID!=0){
            $Where .= " AND gc.ID='$GroupID' ";
        }


        if ($OrderType == '' || $OrderField == '') {
            $OrderField = 'c.ID';
            $OrderType = 'DESC';
        } else {
            $OrderField = 'c.' . $OrderField;
        }

        $UserID = $this->m_User->ID;
        $Count = Db::table('client')->alias('c')->leftJoin('group_client gc','gc.ID=c.GroupID')->where("c.IsDeleted='0' AND c.OwnerID='$UserID' AND c.OwnerType='1' $Where ")->count();
        $Data = Db::table('client')->field("c.*, gc.ID AS GroupID, gc.Name AS GroupName")->alias('c')
            ->leftJoin('group_client gc','gc.ID=c.GroupID')
            ->where("c.IsDeleted='0' AND c.OwnerID='$UserID' AND c.OwnerType='1' $Where ")->page($Page, $Limit)->order($OrderField, $OrderType)->select();
        mb_OutMessage(ErrCode_Normal, '', $Data, $Count);
    }

    /**
     * 公海客戶
     */
    public function mb_PubClientList()
    {
//        $Page = Request::has('page') ? Request::param('page') : 1;
//        $Limit = Request::has('limit') ? Request::param('limit') : 10;
//        $Begin = ($Page - 1) * $Limit;
//
//        $UserID = $this->m_User->ID;
//        $Count = Db::query("SELECT IFNULL(COUNT(uc.ID),0) AS Count "
//            . "FROM company_client AS uc "
//            . "LEFT JOIN client AS c ON c.ID=uc.ClientID "
//            . "WHERE uc.IsDeleted='0' AND uc.UserID='$UserID'")[0]['Count'];
//        $Data = Db::query("SELECT uc.ID, c.Name, c.Deal, c.Remark, c.Source, c.Next, c.Level, c.Industry, c.TimeCreated, c.Follow, c.Email, c.Phone, c.Address "
//            . "FROM company_client AS uc "
//            . "LEFT JOIN client AS c ON c.ID=uc.ClientID "
//            . "WHERE uc.IsDeleted='0' AND uc.UserID='$UserID' ORDER BY ID DESC LIMIT $Begin , $Limit ;");
//
//        mb_OutMessage(ErrCode_Normal, '', $Data, $Count);

        $Page = Request::has('page') ? Request::param('page') : 1;
        $Limit = Request::has('limit') ? Request::param('limit') : 10;
        $Keyword = Request::has('Keyword') ? Request::param('Keyword') : '';
        $Date = Request::has('Date') ? Request::param('Date') : '';

        $OrderField = Request::has('OrderField') ? Request::param('OrderField') : '';
        $OrderType = Request::has('OrderType') ? Request::param('OrderType') : '';

        $Where = '';
        if ($Keyword != '') {
            $Where .= " AND (Name LIKE '%$Keyword%' OR Phone LIKE '%$Keyword%') ";
        }
        if ($Date != '') {
            $Where .= " AND DATE_FORMAT(TimeCreated,'%Y-%m-%d')='$Date' ";
        }

        if ($OrderType == '' || $OrderField == '') {
            $OrderField = 'ID';
            $OrderType = 'DESC';
        }

        $CompanyID = $this->m_User->CompanyID;
        $Count = Db::table('client')->where("IsDeleted='0' AND OwnerID='$CompanyID' AND OwnerType='0' $Where ")->count();
        $Data = Db::table('client')->where("IsDeleted='0' AND OwnerID='$CompanyID' AND OwnerType='0' $Where ")->page($Page, $Limit)->order($OrderField, $OrderType)->select();
//        foreach ($Data as $Key => $Val) {
//            if ($Val['Deal'] == 0) {
//                $Data[$Key]['DealStatus'] = '<i class="icon-remove-circle" style="color: red"></i>未成交';
//            } else {
//                $Data[$Key]['DealStatus'] = '<i class="icon-ok-circle" style="color: green"></i>已成交';
//            }
//            $Data[$Key]['Source'] = $this->GetSourceName($Val['Source']);
//            $Data[$Key]['IndustryName'] = $this->GetIndustryName($Val['Industry']);
//            $Data[$Key]['LevelName'] = $this->GetLevelName($Val['Level']);
//        }
        mb_OutMessage(ErrCode_Normal, '', $Data, $Count);

    }

    /**
     *
     */
    public function mb_CompanyClient()
    {
        $CompanyID = $this->m_User->CompanyID;
        $Page = Request::has('page') ? Request::param('page') : 1;
        $Limit = Request::has('limit') ? Request::param('limit') : 10;
        $Keyword = Request::has('Keyword') ? Request::param('Keyword') : '';
        $Date = Request::has('Date') ? Request::param('Date') : '';
        $StaffID = Request::has('StaffID') ? Request::param('StaffID') : 0;

        $OrderField = Request::has('OrderField') ? Request::param('OrderField') : '';
        $OrderType = Request::has('OrderType') ? Request::param('OrderType') : '';

        $Where = '';
        if ($Keyword != '') {
            $Where .= " AND (Name LIKE '%$Keyword%' OR Phone LIKE '%$Keyword%') ";
        }
        if ($Date != '') {
            $Where .= " AND DATE_FORMAT(TimeCreated,'%Y-%m-%d')='$Date' ";
        }
        if ($StaffID == 0) {
            //查找公司所有客户
            $Where .= " AND ((OwnerType='0' AND OwnerID='$CompanyID') OR (OwnerType='1' AND OwnerID IN (SELECT ID FROM user WHERE IsDeleted='0' AND CompanyID='$CompanyID')))";
        } else if ($StaffID == -1) {
            //查找公海客户
            $Where .= " AND OwnerType='0' AND OwnerID='$CompanyID'";
        } else {
            //查找员工客户
            $Where .= " AND OwnerType='1' AND OwnerID='$StaffID'";
        }

        if ($OrderType == '' || $OrderField == '') {
            $OrderField = 'ID';
            $OrderType = 'DESC';
        }

        $StaffData = Db::table('user')->field('ID,Nick')->where("IsDeleted='0' AND CompanyID='$CompanyID'")->select();

        $Count = Db::table('client')->where("IsDeleted='0' $Where ")->count();
        $Data = Db::table('client')->where("IsDeleted='0' $Where")->page($Page)->limit($Limit)->order($OrderField, $OrderType)->select();

        foreach ($Data as $Key => $Val) {
//
//            if ($Val['Deal'] == 0) {
//                $Data[$Key]['DealStatus'] = '<i class="icon-remove-circle" style="color: red"></i>未成交';
//            } else {
//                $Data[$Key]['DealStatus'] = '<i class="icon-ok-circle" style="color: green"></i>已成交';
//            }
//            $Data[$Key]['Source'] = $this->GetSourceName($Val['Source']);
//            $Data[$Key]['IndustryName'] = $this->GetIndustryName($Val['Industry']);
//            $Data[$Key]['LevelName'] = $this->GetLevelName($Val['Level']);

            if ($Val['OwnerType'] == 0) {
                $Data[$Key]['InCharge'] = '公海';
            } else {
                foreach ($StaffData as $sKey => $sVal) {
                    if ($Val['OwnerID'] == $sVal['ID']) {
                        $Data[$Key]['InCharge'] = $sVal['Nick'];
                        break;
                    }
                }
                if (isset($Data[$Key]['InCharge']) == false) {
                    //该用户已被删除
                    $Data[$Key]['InCharge'] = '公海';
                }
            }
        }
        mb_OutMessage(ErrCode_Normal, '', $Data, $Count);
    }

    /**
     * 添加或编辑客户
     */
    public function mb_AddEditClient()
    {
        $ClientID = Request::has('ClientID') ? Request::param('ClientID') : 0;  //客户ID，0：新增，Other：编辑
        $Type = Request::has('Type') ? Request::param('Type') : 'my';
        $Name = Request::has('Name') ? Request::param('Name') : '';
        $Level = Request::has('Level') ? Request::param('Level') : '';
        $Industry = Request::has('Industry') ? Request::param('Industry') : '';
        $Source = Request::has('Source') ? Request::param('Source') : '';
        $Contacts = Request::has('Contacts') ? Request::param('Contacts') : '';
        $Phone = Request::has('Phone') ? Request::param('Phone') : '';
        $Web = Request::has('Web') ? Request::param('Web') : '';
        $Next = Request::has('Next') ? Request::param('Next') : '';
        $Remark = Request::has('Remark') ? Request::param('Remark') : '';
        $Email = Request::has('Email') ? Request::param('Email') : '';
        $Address = Request::has('Address') ? Request::param('Address') : '';

        if (!$Name) {
            mb_OutMessage(ErrCode_Toast, '请输入客户名称');
            return false;
        }
        if (!$Phone) {
            mb_OutMessage(ErrCode_Toast, '请输入电话号码');
            return false;
        }

        if ($Type != 'my' && $Type != 'pub') {
            mb_OutMessage(ErrCode_Toast, '参数有误');
            return false;
        }

        Db::startTrans();
        try {
            $Data = array(
                'Name' => $Name,
                'Level' => $Level,
                'Industry' => $Industry,
                'Source' => $Source,
                'Contacts' => $Contacts,
                'Phone' => $Phone,
                'Web' => $Web,
                'Next' => $Next,
                'Remark' => $Remark,
                'Email' => $Email,
                'Address' => $Address
            );
            if ($ClientID == 0) {
                if ($Type == 'my') {
                    //添加到我的客户
                    $Data['OwnerID'] = $this->m_User->ID;
                    $Data['OwnerType'] = 1;
                } else {
                    $Data['OwnerID'] = $this->m_User->CompanyID;
                    $Data['OwnerType'] = 0;
                }
                //插入到客户列表
                Db::table('client')->insert($Data);
            } else {
                $Data['ID'] = $ClientID;
                Db::table('client')->update($Data);
            }
            Db::commit();
            mb_OutMessage(ErrCode_Normal, '保存成功');
        } catch (\Exception $e) {
            Db::rollback();
            mb_OutMessage(ErrCode_Toast, $e->getMessage());
        }
    }

    private function mb_FilterClient($Filters, $Info)
    {
        foreach ($Filters as $Key => $Val) {
            if ($Val == '') continue;
            if ($Info == '') continue;
            if (strpos($Info, $Val) !== false) {
                return true;
            } else {
                return false;
            }
        }
        return false;
    }

    /**
     * 導入客戶
     */
    public function mb_ImportClient()
    {
        $Type = Request::has('Type') ? Request::param('Type') : 'my';
        $File = Request::file('ExcelFile');
        $Info = $File->move('./uploads/files');
        $Filter = Request::has('Filter') ? Request::param('Filter') : '';   //要过滤的关键字
        $Filters = explode(',', $Filter);

        $DistinctPhone = Request::has('DistinctPhone') ? Request::param('DistinctPhone') : 0;   //电话去重
        $GroupID = Request::has('GroupID') ? Request::param('GroupID') : 0; //导入分组

        if ($Info) {
//            echo $_SERVER['DOCUMENT_ROOT'].'/uploads/files/'.$Info->getSaveName();
            $Data = Tools::mb_ImportExcel($_SERVER['DOCUMENT_ROOT'] . '/uploads/files/' . $Info->getSaveName());

            if (count($Data) <= 1) mb_OutMessage(ErrCode_Toast, '请填写相关数据');
            if (count($Data[0]) != 11) mb_OutMessage(ErrCode_Toast, '请按照《客户导入模板》整理数据');

            Db::startTrans();
            try {
                $Send = array();
                $Send['FilterCount'] = 0;
                $Send['SuccessCount'] = 0;
                $Send['Failure'] = array();
                $Send['FailureCount'] = 0;
                for ($i = 0; $i < count($Data); $i++) {
                    if ($i == 0) continue;
                    $Val = $Data[$i];
                    $Name = $Val[0];
                    $Level = $Val[1];
                    $Industry = $Val[2];
                    $Source = $Val[3];
                    $Contacts = $Val[4];
                    $Phone = $Val[5];
                    $Email = $Val[6];
                    $Address = $Val[7];
                    $Web = $Val[8];
                    $Next = $Val[9];
                    $Remark = $Val[10];

                    if ($this->mb_FilterClient($Filters, $Name)) {
                        $Send['FilterCount']++;
                        continue;
                    }
                    if ($this->mb_FilterClient($Filters, $Contacts)) {
                        $Send['FilterCount']++;
                        continue;
                    }
                    if ($this->mb_FilterClient($Filters, $Phone)) {
                        $Send['FilterCount']++;
                        continue;
                    }


                    if ($Name == '') {
                        $Send['Failure'][] = array(
//                            'Line' => $i + 1,
//                            'Key' => 'Name',
                            'Msg' => '第' . ($i + 1) . '行错误：请输入客户名称'
                        );
                        $Send['FailureCount']++;
                        continue;
                    }
                    if ($Phone == '') {
                        $Send['Failure'][] = array(
//                            'Line' => $i + 1,
//                            'Key' => 'Phone',
                            'Msg' => '第' . ($i + 1) . '行错误：请输入电话号码'

                        );
                        $Send['FailureCount']++;
                        continue;
                    }

                    if ($Type == 'my') {
                        $UserID = $this->m_User->ID;
//                        $ClientData = Db::query("SELECT c.ID FROM user_client AS uc LEFT JOIN client AS c ON c.ID = uc.ClientID WHERE uc.IsDeleted='0' AND c.Name ='$Name' AND c.Phone='$Phone' AND uc.UserID='$UserID' ;");
                        $ClientData = Db::query("SELECT ID FROM client WHERE IsDeleted='0' AND Name ='$Name' AND OwnerID='$UserID' AND OwnerType='1';");
                        if (count($ClientData) > 0) {
                            $Send['Failure'][] = array(
                                'Value' => $ClientData[0]['ID'],
                                'Msg' => '第' . ($i + 1) . '行错误：该客户名称已存在'
                            );
                            $Send['FailureCount']++;
                            continue;
                        }
                        if($DistinctPhone !=0){
                            $ClientData = Db::query("SELECT ID FROM client WHERE IsDeleted='0' AND Phone ='$Phone'  AND OwnerID='$UserID' AND OwnerType='1';");
                            if (count($ClientData) > 0) {
                                $Send['Failure'][] = array(
                                    'Value' => $ClientData[0]['ID'],
                                    'Msg' => '第' . ($i + 1) . '行错误：该客户电话号码已存在'
                                );
                                $Send['FailureCount']++;
                                continue;
                            }
                        }
                    } else {
                        $CompanyID = $this->m_User->CompanyID;
//                        $ClientData = Db::query("SELECT c.ID FROM company_client AS uc LEFT JOIN client AS c ON c.ID = uc.ClientID WHERE uc.IsDeleted='0' AND c.Name ='$Name' AND c.Phone='$Phone' AND uc.CompanyID='$CompanyID';");
                        $ClientData = Db::query("SELECT ID FROM client WHERE IsDeleted='0' AND Name ='$Name' AND OwnerID='$CompanyID' AND OwnerType='0';");
                        if (count($ClientData) > 0) {
                            $Send['Failure'][] = array(
                                'Value' => $ClientData[0]['ID'],
                                'Msg' => '第' . ($i + 1) . '行错误：该客户名称已存在'
                            );
                            $Send['FailureCount']++;
                            continue;
                        }
                        if ($DistinctPhone != 0) {
                            $ClientData = Db::query("SELECT ID FROM client WHERE IsDeleted='0' AND Phone ='$Phone' AND OwnerID='$CompanyID' AND OwnerType='0';");
                            if (count($ClientData) > 0) {
                                $Send['Failure'][] = array(
                                    'Value' => $ClientData[0]['ID'],
                                    'Msg' => '第' . ($i + 1) . '行错误：该客户电话号码已存在'
                                );
                                $Send['FailureCount']++;
                                continue;
                            }
                        }
                    }
                    $Insert = array(
                        'Name' => $Name,
                        'Level' => $this->GetLevelNum($Level),
                        'Industry' => $this->GetIndustryNum($Industry),
                        'Source' => $this->GetSourceNum($Source),
                        'Contacts' => $Contacts,
                        'Phone' => $Phone,
                        'Web' => $Web,
                        'Next' => $Next,
                        'Remark' => $Remark,
                        'Email' => $Email,
                        'Address' => $Address
                    );
                    if ($Type == 'my') {
                        $Insert['GroupID'] = $GroupID;
                        $Insert['OwnerID'] = $this->m_User->ID;
                        $Insert['OwnerType'] = 1;
                    } else {
                        $Insert['GroupID'] = $GroupID;
                        $Insert['OwnerID'] = $this->m_User->CompanyID;
                        $Insert['OwnerType'] = 0;
                    }
                    Db::table('client')->insert($Insert);

                    $Send['SuccessCount']++;

                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                mb_OutMessage(ErrCode_Toast, $e->getMessage());
            }
            unlink($_SERVER['DOCUMENT_ROOT'] . '/uploads/files/' . $Info->getSaveName());
            mb_OutMessage(ErrCode_Normal, '', $Send);
        } else {
            mb_OutMessage(ErrCode_Toast, $File->getError());
        }
    }

    /**
     * 导出客户
     */
    public function mb_ExportClient()
    {
        $CompanyID = $this->m_User->CompanyID;
        $Type = Request::has('Type') ? Request::param('Type') : 'my';
        $IDs = Request::has('IDs') ? Request::param('IDs') : '';

        $Where = '';
        if ($IDs != 0) {
            //导出部分
            $Where .= " AND ID IN ($IDs) ";
        }

        if ($Type == 'my') {
            $OwnerID = $this->m_User->ID;
            $OwnerType = 1;
            $Where .= " AND OwnerID='$OwnerID' AND OwnerType='$OwnerType' ";
        } else if ($Type == 'pub') {
            $OwnerID = $this->m_User->CompanyID;
            $OwnerType = 0;
            $Where .= " AND OwnerID='$OwnerID' AND OwnerType='$OwnerType' ";
        } else {
            $Where .= " AND ((OwnerType='0' AND OwnerID='$CompanyID') OR (OwnerType='1' AND OwnerID IN (SELECT ID FROM user WHERE IsDeleted='0' AND CompanyID='$CompanyID')))";
        }
        $Data = Db::query("SELECT * FROM client WHERE IsDeleted='0' $Where ;");
        $SetWidths = [30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30];
        $Titles = ['客户名称', '客户级别', '客户行业', '客户来源', '联系人', '电话号码', '邮箱', '地址', '网址', '下次联系时间', '备注',];
        $Contents = array();
        foreach ($Data as $Key => $Val) {
            $Temp = array(
                $Val['Name'],
                $this->GetLevelName($Val['Level']),
                $this->GetIndustryName($Val['Industry']),
                $this->GetSourceName($Val['Source']),
                $Val['Contacts'],
                $Val['Phone'],
                $Val['Email'],
                $Val['Address'],
                $Val['Web'],
                $Val['Next'],
                $Val['Remark']
            );
            $Contents[] = $Temp;
        }
        $FileName = '客户资料导出_' . date('YmdHis') . '_' . rand(100, 999) . '.xls';

        Tools::mb_ExportExcel($Titles, $Contents, $_SERVER['DOCUMENT_ROOT'] . '/uploads/files/' . $FileName, $SetWidths);
        mb_OutMessage(ErrCode_Normal, '导出成功', ['url' => Request::domain() . '/uploads/files/' . $FileName]);
    }

    /**
     * 转移客户
     */
    public function mb_ChangeClientOwner()
    {
        $OwnerID = Request::has('OwnerID') ? Request::param('OwnerID') : '';
        $Type = Request::has('Type') ? Request::param('Type') : '';
        $IDs = Request::has('IDs') ? Request::param('IDs') : '';
        Db::startTrans();
        try {
            if ($Type == 'my') {
                if (!$OwnerID) $OwnerID = $this->m_User->ID;
                $OwnerType = 1;
            } else {
                if (!$OwnerID) $OwnerID = $this->m_User->CompanyID;
                $OwnerType = 0;
            }

            Db::execute("UPDATE client SET OwnerID='$OwnerID', OwnerType='$OwnerType' WHERE ID IN ($IDs);");
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            mb_OutMessage(ErrCode_Toast, $e->getMessage());
        }
        mb_OutMessage(ErrCode_Normal, '转移成功');
    }

    /**
     * 改变客户成交状态
     */
    public function mb_ChangeClientDeal()
    {
        $Deal = Request::has('Deal') ? Request::param('Deal') : '';
        $IDs = Request::has('IDs') ? Request::param('IDs') : '';
        Db::startTrans();
        try {
            Db::execute("UPDATE client SET Deal='$Deal' WHERE ID IN ($IDs);");
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            mb_OutMessage(ErrCode_Toast, $e->getMessage());
        }
        mb_OutMessage(ErrCode_Normal, '改变成功');
    }

    /**
     * 添加到拨打列表
     */
    public function mb_AddCall()
    {
        $ClientID = Request::has('ClientID') ? Request::param('ClientID') : 0;
        if (!$ClientID) {
            mb_OutMessage(ErrCode_Toast, '参数有误');
        }
        $UserID = $this->m_User->ID;
        Db::startTrans();
        try {
            $Insert = array(
                'UserID' => $UserID,
                'ClientID' => $ClientID
            );
            Db::table('user_calls')->insert($Insert);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            mb_OutMessage(ErrCode_Toast, $e->getMessage());
        }
        mb_OutMessage(ErrCode_Normal, '添加成功');
    }

    /**
     * 待拨打列表
     */
    public function mb_CallList()
    {
        $UserID = $this->m_User->ID;
        $Page = Request::has('page') ? Request::param('page') : 1;
        $Limit = Request::has('limit') ? Request::param('limit') : 10;
        $Keyword = Request::has('Keyword') ? Request::param('Keyword') : '';

        $Where = '';
        if ($Keyword != '') {
            $Where .= " AND (c.Name LIKE '%$Keyword%' OR c.Phone LIKE '%$Keyword%') ";
        }

        $Count = Db::table('user_calls')->alias('uc')->leftJoin('client c', 'c.ID=uc.ClientID')->where("uc.IsDeleted='0' AND uc.UserID='$UserID' $Where ")->count();
        $Data = Db::table('user_calls')->field('uc.ID,uc.ClientID,c.Name AS ClientName,c.Contacts,uc.IsCalled,uc.TimeCreated')->alias('uc')
            ->leftJoin('client c', 'c.ID=uc.ClientID')->where("uc.IsDeleted='0' AND uc.UserID='$UserID' $Where ")->order('ID', 'DESC')
            ->page($Page)->limit($Limit)->select();
        foreach ($Data as $Key => $Val) {
            if ($Val['IsCalled'] == 0) $Data[$Key]['IsCalledStr'] = '<label style="color: red;">等待拨号...</label>';
            else $Data[$Key]['IsCalledStr'] = '<label style="color: green">已拨号</label>';
        }

        mb_OutMessage(ErrCode_Normal, '', $Data, $Count);
    }

    public function mb_CallRecord()
    {
        $UserID = $this->m_User->ID;
        $Page = Request::has('page') ? Request::param('page') : 1;
        $Limit = Request::has('limit') ? Request::param('limit') : 10;
        $Keyword = Request::has('Keyword') ? Request::param('Keyword') : '';
        $Where = '';
        if ($Keyword != '') {
            $Where .= " AND (c.Name LIKE '%$Keyword%' OR c.Phone LIKE '%$Keyword%') ";
        }

        $Count = Db::table('user_call_records')->alias('ucr')->leftJoin('client c', 'c.ID=ucr.ClientID')->where("ucr.IsDeleted='0' AND ucr.UserID='$UserID' $Where ")->count();
        $Data = Db::table('user_call_records')->field('ucr.ID,ucr.ClientID,c.Name AS ClientName,c.Contacts,ucr.Status,ucr.TimeCreated,ucr.TalkTime,ucr.VoiceUrl')->alias('ucr')
            ->leftJoin('client c', 'c.ID=ucr.ClientID')->where("ucr.IsDeleted='0' AND ucr.UserID='$UserID' $Where ")->order('ucr.ID', 'DESC')
            ->page($Page)->limit($Limit)->select();
        foreach ($Data as $Key => $Val) {
            if ($Val['Status'] == 0) $Data[$Key]['StatusStr'] = '<label style="color: orange;">未接听</label>';
            else if ($Val['Status'] == 1) $Data[$Key]['StatusStr'] = '<label style="color: orange">电话拒接</label>';
            else $Data[$Key]['StatusStr'] = '<label style="color: green">已接听</label>';

            $m = intval($Val['TalkTime'] / 60);
            $s = $Val['TalkTime'] % 60;
            $Data[$Key]['TalkTimeStr'] = $m . '分';
            if ($s != 0) $Data[$Key]['TalkTimeStr'] .= $s . '秒';
        }

        mb_OutMessage(ErrCode_Normal, '', $Data, $Count);
    }

    /**
     * 跟进客户
     */
    public function mb_FollowClient()
    {
        $ID = Request::has('ID') ? Request::param('ID') : 0;
        $Field = Request::has('Field') ? Request::param('Field') : '';
        $Value = Request::has('Value') ? Request::param('Value') : '';

        Db::startTrans();
        try {
            Db::table('client')->update(array(
                'ID' => $ID,
                $Field => $Value
            ));
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            mb_OutMessage(ErrCode_Toast, $e->getMessage());
        }
        mb_OutMessage(ErrCode_Normal, '保存成功');
    }

    #endregion

    private function GetSourceName($Source)
    {
        $Name = '';
        switch ($Source) {
            case 1:
                $Name = '促销活动';
                break;
            case 2:
                $Name = '搜索引擎';
                break;
            case 3:
                $Name = '广告';
                break;
            case 4:
                $Name = '转介绍';
                break;
            case 5:
                $Name = '线上注册';
                break;
            case 6:
                $Name = '线上询价';
                break;
            case 7:
                $Name = '预约上门';
                break;
            case 8:
                $Name = '陌拜';
                break;
            case 9:
                $Name = '招商资源';
                break;
            case 10:
                $Name = '公司资源';
                break;
            case 11:
                $Name = '展会资源';
                break;
            case 12:
                $Name = '个人资源';
                break;
            case 13:
                $Name = '电话咨询';
                break;
            case 14:
                $Name = '邮件咨询';
                break;
            default:
                break;
        }
        return $Name;
    }

    private function GetIndustryName($Industry)
    {
        $Name = '';
        switch ($Industry) {
            case 1:
                $Name = 'IT/通信/电子/互联网';
                break;
            case 2:
                $Name = '金融业';
                break;
            case 3:
                $Name = '房产业';
                break;
            case 4:
                $Name = '商业服务';
                break;
            case 5:
                $Name = '贸易';
                break;
            case 6:
                $Name = '生产';
                break;
            case 7:
                $Name = '运输物品';
                break;
            case 8:
                $Name = '服务业';
                break;
            case 9:
                $Name = '文化传媒';
                break;
            case 10:
                $Name = '政府';
                break;
            case 11:
                $Name = '其他';
                break;
        }
        return $Name;
    }

    private function GetLevelName($Level)
    {
        $Name = 'A类（重点客户）';
        switch ($Level) {
            case 'B':
                $Name = 'B类（普遍客户）';
                break;
            case 'C':
                $Name = 'C类（非优先客户）';
                break;
        }
        return $Name;
    }

    private function GetSourceNum($Source)
    {
        $Name = 0;
        switch ($Source) {
            case '促销活动':
                $Name = 1;
                break;
            case '搜索引擎':
                $Name = 2;
                break;
            case '广告':
                $Name = 3;
                break;
            case '转介绍':
                $Name = 4;
                break;
            case '线上注册':
                $Name = 5;
                break;
            case '线上询价':
                $Name = 6;
                break;
            case '预约上门':
                $Name = 7;
                break;
            case '陌拜':
                $Name = 8;
                break;
            case '招商资源':
                $Name = 9;
                break;
            case '公司资源':
                $Name = 10;
                break;
            case '展会资源':
                $Name = 11;
                break;
            case '个人资源':
                $Name = 12;
                break;
            case '电话咨询':
                $Name = 13;
                break;
            case '邮件咨询':
                $Name = 14;
                break;
            default:
                break;
        }
        return $Name;
    }

    private function GetIndustryNum($Industry)
    {
        $Name = 0;
        switch ($Industry) {
            case 'IT/通信/电子/互联网':
                $Name = 1;
                break;
            case '金融业':
                $Name = 2;
                break;
            case '房产业':
                $Name = 3;
                break;
            case '商业服务':
                $Name = 4;
                break;
            case '贸易':
                $Name = 5;
                break;
            case '生产':
                $Name = 6;
                break;
            case '运输物品':
                $Name = 7;
                break;
            case '服务业':
                $Name = 8;
                break;
            case '文化传媒':
                $Name = 9;
                break;
            case '政府':
                $Name = 10;
                break;
            case '其他':
                $Name = 11;
                break;
        }
        return $Name;
    }

    private function GetLevelNum($Level)
    {
        $Name = 'B';
        switch ($Level) {
            case 'A类（重点客户）':
                $Name = 'A';
                break;
            case 'C类（非优先客户）':
                $Name = 'C';
                break;
        }
        return $Name;
    }
}